/**
* @description: 待办工单 -》 通信光缆巡视 -》 已巡视详情 -》 已核查纤芯详情
**/

<template>
  <div class="power-detail-wrap">
    <nav-bar class="header" back title="纤芯详情" @goBack="goBack"/>

    <!-- 纤芯信息 -->
    <div class="power-info">
      <plateTitle title="纤芯信息" class="plate-title-1"/>
      <view class="base-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in fiberData.baseInfoData" :key="index" :title="item.title" :value="item.value" />
        </van-cell-group>
      </view>

      <!--光路信息（"被占用"时显示）-->
      <div v-if="fiberData.originData && fiberData.originData.IS_OCCUPY !== '5' && fiberData.originData.IS_OCCUPY !== '6'">
        <plateTitle title="光路信息" class="plate-title-2 with-tag">
          <div class="info-tag"
               :class="isMatch ? 'bg-green': 'bg-red'"
                v-if="isUpdate">
            {{ isMatch ? "光路信息匹配成功" : "设备信息不确认"}}
          </div>
        </plateTitle>
        <div class="base-info-container" style="min-height: 40px">
          <!--暂无数据("更新状态"&&"光路不匹配")-->
          <div v-if="!isMatch && isUpdate" style="padding: 16px;text-align: center;">暂无数据</div>
          <!--光路基本信息("更新状态"&&"光路匹配成功" 或 "其他状态")-->
          <van-cell-group v-if="(isUpdate && isMatch) || !isUpdate">
            <van-cell v-for="(item,index) in circuitData.baseInfoData" :key="index" :title="item.title" :value="item.value" />
          </van-cell-group>
        </div>
      </div>

      <!--核查信息（"已核查/已完善"时显示）-->
      <div>
        <plateTitle title="巡视信息" :isRequired="false" class="plate-title-2"/>
        <!-- 本端现场标签信息 -->
        <view class="tag-info-container" v-if="isUpdate && isOccupied">
          <view>本端现场标签信息</view>
          <van-divider dashed />
          <div class="tag-wrap">
            {{patrolData.originData.LABEL}}
          </div>
        </view>

        <!-- 巡视照片 -->
        <view class="patrol-info-container" v-if="isUpdate">
          <view>巡视照片</view>
          <van-divider dashed />
          <div v-if="files.filter(item => item.img).length === 0" style="text-align: center;">暂无数据</div>
          <div v-else class="image-wrap">
            <div class="image-list">
              <div
                class="upload-button"
                v-for="(imgItem, index) in files"
                :style="{'background-image': `url(${imgItem.bgImg})`}"
                v-if="imgItem.img"
              >
                <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, index, 'PREVIEW')">
              </div>
            </div>
          </div>
        </view>

        <!-- 备注 -->
        <view class="remark-info-container" v-if="isUpdate">
          <view>备注</view>
          <van-divider dashed />
          <div class="remark-wrap">
          <textarea class="remark-text" disabled :value="patrolData.originData.REMARK">
          </textarea>
          </div>
        </view>

        <!-- 巡视结果 -->
        <view class="result-info-container">
          <van-cell-group>
            <van-cell v-for="(item,index) in patrolData.baseInfoData" :key="index" :title="item.title" :value="item.value" :class="item.color" />
          </van-cell-group>
        </view>
        <van-button block v-if="isEditable" @click="reEdit">重新编辑</van-button>

        <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
          <van-swipe>
            <div v-for="(image, index) in files" :key="index">
              <van-swipe-item v-if="image.img" style="text-align: center;">
                <div style="width: 100%; text-align: center;">{{ image.previewName }}</div>
                <img :src="image.img" />
              </van-swipe-item>
            </div>
          </van-swipe>
        </van-popup>

      </div>
    </div>

  </div>
</template>

<script>
import navBar from "../../../../../components/common/nav-bar";
import plateTitle from '../../../../../components/business/plateTitle.vue';
import config from "../../../../../common/config";
import { merge } from "lodash";


// 纤芯信息-已占用
let map_fiber_occupied = {
  "FIBER_NAME": "所属光缆",           //	String	所属光缆
  "IS_OCCUPY_NAME": "是否占用",    //	String	是否占用
  "CORE_PD_ARRANGE": "配对纤芯"
}

// 纤芯信息-未占用
let map_fiber_unoccupied = {
  "FIBER_NAME": "所属光缆",   //	String	所属光缆
  "IS_OCCUPY_NAME": "是否占用",    //	String	是否占用
  "LENGTH": "测试长度(km)",
  "LOSS": "全程总损耗(dB)",
  "IS_SMOOTHNESS": "曲线是否平滑",
  "BREAKPOINT": "断点位置",
};

// 光路信息
let map_circuit = {
  "LIGHT_NAME": "光路名称",
  "A_EQU_NAME": "A端设备名称",
  "A_PORT": "A端设备端口",
  "Z_EQU_NAME": "Z端设备名称",
  "Z_PORT": "Z端设备端口",
  "MAIN_PREPARE": "主备光路",
};

// 巡视结果
let map_patrol = {
  "TOUR_STATE": "巡视结果",
  "TOUR_OPER_NAME": "巡视人",
  "TOUR_TIM": "巡视时间",
}
let fileTemplate = [
  {
    name: "EQUIPMENT.jpg",
    previewName: "设备照片",
    type: "EQUIPMENT",
    bgImg: require("../../../../../static/img/bg_shebei.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "NAMEPLATE.jpg",
    previewName: "铭牌照片",
    type: "NAMEPLATE",
    bgImg: require("../../../../../static/img/bg_mingpai.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "OTHER.jpg",
    previewName: "其他照片",
    type: "OTHER",
    bgImg: require("../../../../../static/img/bg_qita.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];

export default {
  name: "fiberDetail", // 通信电源详情
  data () {
    return {
      loadOptions: {}, // 页面接收的传参
      fiberData: {}, // 纤芯信息
      circuitData: {}, // 光路信息
      patrolData: {}, // 巡视信息
      isOccupied: false, // 纤芯是否占用
      isUpdate: false, // 巡视状态是否为更新
      isMatch: false, // 光路信息是否匹配成功
      baseUrl: "", // 基础url
      isEditable: false, // 是否可重新编辑
      files: fileTemplate,
      showPreview: false,
    }
  },
  components: {
    navBar,
    plateTitle,
  },
  onLoad(rawOptions) {
    this.loadOptions = JSON.parse(rawOptions.fiberInfo);
    this.getLineDetailes(this.loadOptions);
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
    })
  },
  methods: {
    goBack() {
      // uni.navigateTo({
      //   url: `/pages/workBench/todoTask/cableTour/cableDetail/cableDetail?tourId=${this.loadOptions.PAR_OPT}`
      // });
      uni.navigateBack();
    },
    // 获取纤芯详情
    getLineDetailes(options) {
      let params = {
        "service_state": options.SERVICE_STATE, // 设备状态
        "is_occupy": options.IS_OCCUPY, // 纤芯占用
        "line_exam_id": options.OBJ_ID // 纤芯巡视id
      };
      this.$api.todoTaskApi.lineDetailes(params).then(res => {
        if(res.code === 0) {
          // 如果当前项为当前操作人巡视完成的，状态为未完成，设备状态为更新或新增，则显示编辑按钮支持编辑，并且状态为未完成，则显示编辑按钮支持编辑
          this.isEditable = (
            res.data.line_exam_msg.TOUR_OPER_ID === this.$store.state.userData.userId &&
            res.data.lineMsg.TASK_DET_STATE !== '99' &&
            (res.data.lineMsg.SERVICE_STATE === 3 || res.data.lineMsg.SERVICE_STATE === 4)
          )
          let fiberMap;
          // 判断纤芯是否占用
          if (res.data.lineMsg.IS_OCCUPY === "5" || res.data.lineMsg.IS_OCCUPY === undefined) {
            this.isOccupied = false;
            fiberMap = map_fiber_unoccupied;
          } else {
            this.isOccupied = true;
            fiberMap = map_fiber_occupied;
          }
          // 判断光路信息是否匹配成功
          res.data.lineMsg.TOUR_BEARFRUIT === 2 ? this.isMatch = true : this.isMatch = false;
          // 纤芯信息
          this.fiberData = {
            originData: res.data.lineMsg,
            baseInfoData: Object.keys(fiberMap).map(key => {
              return {
                title: fiberMap[key],
                value: res.data.lineMsg[key]
              }
            })
          };
          // 光路信息
          this.circuitData = res.data.line_channel ? {
            originData: res.data.line_channel,
            baseInfoData: Object.keys(map_circuit).map(key => {
              return {
                title: map_circuit[key],
                value: res.data.line_channel[key]
              }
            })
          } : {};

          // 判断纤芯是否是更新状态
          res.data.line_exam_msg.TOUR_STATE === "更新" ? this.isUpdate = true : this.isUpdate = false;
          // 巡视信息
          this.patrolData = {
            originData: res.data.line_exam_msg,
            baseInfoData: Object.keys(map_patrol).map(key => {
              let value = res.data.line_exam_msg[key];
              let color = "";
              (value === "一致") && (color = "blue");
              (value === "新增") && (color = "green");
              (value === "不存在") && (color = "red");
              (value === "更新") && (color = "yellow");
              return {
                title: map_patrol[key],
                value: value,
                color: color
              };
            }),
          };
          console.log(this.patrolData,323232)
          this.files = this.files.map((item) => {
            return {
              ...item,
              img: res.data.lineMsg.photoMap[item.type] ? this.baseUrl + res.data.lineMsg.photoMap[item.type]: '',
            }
          })
        }
      });
    },
    imageHandle (imgItem, imgIndex, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除${imgItem.previewName}`
        })
          .then(() => {
            this.$set(this.files, imgIndex, {
              ...this.files[imgIndex],
              raw: null,
              img: ''
            })
            this.delList.includes(imgItem.type) ? null: this.delList.push(imgItem.type);
              console.log(this.delList, "delete")

          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto(imgItem, imgIndex) {
      let _this = this;
      wx.chooseImage({
        count: 3,
        sourceType: ["camera"],
        success: (chooseImageRes) => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                    //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                    imageBase64 = localData;
                } else {
                    //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                    //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                    imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                
                _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
                   raw: _this.h5_url_to_blob(imageBase64),
                   img: imageBase64
                }));

                
                if (_this.delList.includes(imgItem.type)) {
                  _this.delList = _this.delList.filter(item => {
                    if (item === imgItem.type) {
                      return false;
                    }
                    
                    return true;
                  });
                }
            }
          });
        },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },

    // 重新编辑
    reEdit() {
      let params = this.fiberData.originData;
      uni.navigateTo({
        url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${params.TASK_ID}&opticalInfo=${JSON.stringify(params)}&source=cableDetail&reTourCheck=0`
      });

      // 设备状态（1 一致  2  不存在  3  新增   4  更新）
      // 判断上次巡视结果，如果为一致/不存在，跳转核查页
      // let params = this.fiberData.originData;
      // if(params.SERVICE_STATE === 1 || params.SERVICE_STATE === 2) {
      //   params.TOUR_STATE = this.loadOptions.TOUR_STATE;
      //   params.CORE_OBJ_ID = this.loadOptions.CORE_OBJ_ID
      //   uni.navigateTo({
      //     url: `/pages/workBench/todoTask/cableTour/cableDetail/fiberInspect?obj=${JSON.stringify(params)}&fiber_exam_id=${params.PAR_OPT}&reTourCheck=0`
      //   })
      // }
      // // 如果为更新/新增，跳转完善页
      // else if(params.SERVICE_STATE === 4 || params.SERVICE_STATE === 3) {
      //   uni.navigateTo({
      //     url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${params.TASK_ID}&opticalInfo=${JSON.stringify(params)}&source=cableDetail&reTourCheck=0`
      //   });
      // }
    }
  }
}
</script>

<style lang="scss" scoped>

.power-detail-wrap {
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  width: 100vw;
  min-height: 100vh;
  background-color: rgba(242,246,250,1);

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }

  .power-state{
    width: 100vw;
    height: px2vh(140);
    background-color: #ffffff;
    box-sizing: border-box;
    padding: 0 px2vw(30) 0 px2vw(49);
    display: flex;
    justify-content: space-between;
    align-items: center;
    .power-state-title {
      font-size: px2vw(42);
    }
    .power-state-text {
      width: px2vw(220);
      height: px2vh(80);
      border-radius: px2vw(40);
      font-size: px2vw(42);
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: bold;
      &.power-state-on {
        color: rgba(255,67,85,1);
        background-color: rgba(255,67,85,0.1);
      }

      &.power-state-off {
        color: rgba(65,220,131,1);
        background-color: rgba(65,220,131,0.1);
      }
    }
  }


  .power-info {
    width: calc(100% - #{px2vw(60)});
    margin: auto;
    padding-bottom: px2vh(30);
    .plate-title-1 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }
    .plate-title-2 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }
    .plate-title-2.with-tag {
      .plate-title-right {
        .info-tag {
          padding: 2px 10px;
          font-size: px2vw(40);
          color: #fff;
          border-radius: 15px;
          overflow: hidden;
        }
        .info-tag.bg-green {
          background-color: #41DC83;
        }
        .info-tag.bg-red {
          background-color: #FF4355;
        }
      }
    }
    .base-info-container, .result-info-container {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
    }

    .result-info-container {
      .yellow {
        /deep/.van-cell__value {
          color: #FFAD0E;
        }
      }
      .blue {
        /deep/.van-cell__value {
          color: #417ADC;
        }
      }
      .green {
        /deep/.van-cell__value {
          color: #41DC83;
        }
      }
      .red {
        /deep/ .van-cell__value {
          color: #FF4355;
        }
      }
    }

    .tag-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      margin-bottom: px2vh(40);
    }

    .remark-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      margin-top: px2vh(40);
      margin-bottom: px2vh(40);
      .remark-wrap {
        background-color: #FAFAFA;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        .remark-text {
          height: px2vh(150);
        }
      }
    }

    .patrol-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;

      /deep/.van-radio {
        margin-right: px2vw(139.5)
      }

      .image-wrap {
        width: 100%;
        display: flex;
        img {
          width: px2vw(215);
          height: px2vw(215);
          margin-right: px2vw(40);
          border-radius: px2vw(6);
        }

        .image-list {
          width: 100%;
          display: flex;
          .upload-button {
            width: px2vw(215);
            height: px2vw(215);
            background-size: cover;
            margin-right: px2vw(40);
            position: relative;
            .delete-icon {
              position: absolute;
              top: px2vw(-20);
              right: px2vw(-20);
              width: px2vw(40);
              height: px2vw(40);
              background-color: rgba(0, 0, 0, 0.7);
              border-radius: 50%;
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }
    }
  }

  .fibre-info {
    .fibre-rate {
      width: calc(100% - #{px2vw(60)});
      height: px2vh(140);
      border-radius: px2vw(20);
      box-sizing: border-box;
      margin: px2vh(40) px2vw(30) px2vh(60);
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .bar-title {
        font-size: px2vw(42);
        color: rgba(65,122,220,1);
        margin-left: px2vw(40);
      }

      .bar-chart {
        width: px2vw(660);
        height: px2vh(34);
        margin: 0 px2vw(27) 0 px2vw(30);
        background-color: #ECF1FB;
        .bar-chart-off {
          width: 75%;
          height: 100%;
          background: repeating-linear-gradient(135deg, #417ADC, #417ADC #{px2vw(16)},#B3CAF1 #{px2vw(16)}, #B3CAF1 #{px2vw(32)});
        }
      }

      .bar-text {
        font-size: px2vw(42);
        margin-right: px2vw(40);
        font-weight: bold;
        color: #7C7C7C;
        .bar-off {
          color: #417ADC;
        }
      }
    }


  }

  .fibre-content-title {
    width: calc(100% - #{px2vw(80)});
    box-sizing: border-box;
    margin: px2vh(0) px2vw(40) px2vh(18);
    .condition-bar {
      display: flex;
      justify-content: center;
      .condition-item {
        height: px2vh(56);
        background-color: rgba(65,122,220,0.1);
        border: #{px2vw(2)} solid rgba(65,122,220,1);
        color: rgba(65,122,220,1);
        border-radius: px2vw(6);
        font-size: px2vw(30);
        padding: 0 px2vw(16) 0 px2vw(19);
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 px2vw(5);
        &:last-child {
          margin-right: 0;
        }
        &.condition-item-checked {
          background-color: rgba(65,122,220,1);
          color: rgba(255,255,255,1);
        }
      }
    }
  }

  .fibre-pair-list {
    .fibre-pair-item {
      width: calc(100% - #{px2vw(60)});
      height: px2vh(140);
      border-radius: px2vw(20);
      box-sizing: border-box;
      margin: px2vh(40) px2vw(30) px2vh(40);
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .replace-index {
        margin: 0 px2vw(28) 0 px2vw(40);
        width: px2vw(64);
        height: px2vw(64);
        border-radius: 50%;
        background: radial-gradient(circle at center,#417ADC, #417ADC #{px2vw(23)}, #ffffff #{px2vw(23)},#ffffff #{px2vw(26)}, #417ADC #{px2vw(26)}, #417ADC 100%);
        color: #ffffff;
        font-size: px2vw(36);
        font-weight: bold;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .replace-text {
        font-size: px2vw(42);
        color: #666666;
      }

      .replace-state {
        font-size: px2vw(42);
        margin-right: px2vw(39);

        &.replace-state-on {
          color: #41DC83;
        }

        &.replace-state-off {
          color: #FF4355;
        }
      }


    }
  }
  /deep/.van-button {
    margin-top: px2vh(30);
    height: px2vh(120);
    color: #fff;
    background-color: #417adc;
    border: 1px solid #417adc;
    border-radius: px2vh(60);
  }
}
</style>
